﻿using Coravel.Invocable;
using CRM.Extensions;
using CRM.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Z.EntityFramework.Plus;

namespace CRM.Jobs
{
    public class AutoMoveToWatersJob : IInvocable
    {
        private readonly MyDbContext _dbContext;
        private readonly ILogger<AutoMoveToWatersJob> _logger;
        public AutoMoveToWatersJob(MyDbContext dbContext, ILogger<AutoMoveToWatersJob> logger)
        {
            _dbContext = dbContext;
            _logger = logger;
        }


        public async Task Invoke()
        {
            var CeilCurrentMinute = DateTime.Now.CurrentMinute().AddMinutes(1);
            var CompanyList = await _dbContext.Company.ToListAsync();
            foreach (var item in CompanyList)
            {
                //自动进入公海时长
                var AutoWatersDay = item.AutoWatersDay;
                var AutoWatersTime = DateTime.Now.AddDays(-AutoWatersDay);

                List<CustomerOperationLog> logs = new() { };

                //无跟进的客户
                var NotFollowCustomerList = await _dbContext.Customer
                    .Where(m => m.OemId == item.OemId && m.CompanyId == item.Id && m.IsPrivate == 1 && m.FollowAt == null && m.UpdatedAt < AutoWatersTime)
                    .ToListAsync();
                var NotFollowBlockIds = NotFollowCustomerList.Select(m => m.BlockId).Distinct().ToList();
                var NotFollowCustomerIds = NotFollowCustomerList.Select(m => m.Id).Distinct().ToList();

                var LogContent = "长时间未跟进，客户移入公海";

                foreach (var NotFollowItem in NotFollowCustomerList)
                {
                    logs.Add(
                        new CustomerOperationLog()
                        {
                            CustomerId = NotFollowItem.Id,
                            Content = LogContent,
                        }
                    );
                }

                //存在跟进的客户
                var ExistFollowCustomerList = await _dbContext.Customer
                    .Where(m => m.OemId == item.OemId && m.CompanyId == item.Id && m.IsPrivate == 1 && m.FollowAt < AutoWatersTime)
                    .ToListAsync();
                var ExistFollowBlockIds = NotFollowCustomerList.Select(m => m.BlockId).Distinct().ToList();
                var ExistFollowCustomerIds = NotFollowCustomerList.Select(m => m.Id).Distinct().ToList();

                foreach (var ExistFollowItem in ExistFollowCustomerList)
                {
                    logs.Add(
                        new CustomerOperationLog()
                        {
                            CustomerId = ExistFollowItem.Id,
                            Content = LogContent,
                        }
                    );
                }
                var Time = DateTime.Now;
                foreach (var log in logs)
                {
                    log.UpdatedAt = Time;
                    log.CreatedAt = Time;
                    log.OemId = item.OemId;
                    log.CompanyId = item.Id;
                    log.GroupId = 0;
                    log.UserId = 0;

                    _dbContext.CustomerOperationLog.Add(log);
                }

                var Transaction = _dbContext.Database.BeginTransaction();
                try
                {

                    _dbContext.CustomerCompany.Where(m => NotFollowBlockIds.Contains(m.Id)).Update(m => new { IsExistPrivate = CustomerCompany.IsExistPrivateType.Yes });

                    _dbContext.Customer.Where(m => NotFollowCustomerIds.Contains(m.Id)).Update(m => new { IsIntention = 0, IsPrivate = 0 });

                    _dbContext.CustomerCompany.Where(m => ExistFollowBlockIds.Contains(m.Id)).Update(m => new { IsExistPrivate = CustomerCompany.IsExistPrivateType.Yes });
                    
                    _dbContext.Customer.Where(m => ExistFollowCustomerIds.Contains(m.Id)).Update(m => new { IsIntention = 0, IsPrivate = 0 });

                    for(var i = 0; i < NotFollowBlockIds.Count; i++)
                    {
                        SetBlock(_dbContext.Customer, _dbContext.CustomerCompany, NotFollowBlockIds[i],item.OemId);
                    }

                    for (var i = 0; i < ExistFollowBlockIds.Count; i++)
                    {
                        SetBlock(_dbContext.Customer, _dbContext.CustomerCompany, NotFollowBlockIds[i], item.OemId);
                    }

                    _dbContext.SaveChanges();
                    Transaction.Commit();
                    _logger.LogInformation("自动移入公海成功");
                }
                catch (Exception e)
                {
                    Transaction.Rollback();
                    _logger.LogInformation($"自动移入公海错误:{e.Message}");
                }

            }
        }

        private void SetBlock(DbSet<Customer> CustomerModel, DbSet<CustomerCompany> CustomerCompanyModel, int BlockId,int OemId)
        {
            //块下面的客户是否全处于公海
            var IsPrivateNum = CustomerModel.Where(m => m.BlockId == BlockId && m.OemId == OemId && m.IsPrivate == 1).Count();
            if (IsPrivateNum == 0)
            {
                CustomerCompanyModel.Where(m => m.Id == BlockId).Update(m => new { IsExistMy = CustomerCompany.IsExistMyType.NO });
            }
            //块下面的客户是否还存在意向客户
            var IsIntentionNum = CustomerModel.Where(m => m.BlockId == BlockId && m.OemId == OemId && m.IsIntention == 1).Count();
            if (IsIntentionNum == 0)
            {
                CustomerCompanyModel.Where(m => m.Id == BlockId).Update(m => new { IsExistIntention = CustomerCompany.IsExistIntentionType.NO });
            }
        }
    }
}
